package com.dreamstations.changshads.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.dreamstations.changshads.R;
import com.dreamstations.changshads.adapter.DSRvAdapter;
import com.dreamstations.changshads.util.DSRequest;
import com.dreamstations.changshads.util.DSUtils;
import com.dreamstations.changshads.util.L;
import com.dreamstations.changshads.util.RequestType;
import com.dreamstations.changshads.view.Slide_Indicator;
import com.squareup.picasso.Picasso;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.recyclerview.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 7YHong on 2016/6/20.
 */
public class Library_Reading_Frag<T> extends Fragment {
    private static final String TAG = Library_Reading_Frag.class.getName();

    private DSRequest dsRequest;
    private int currentPage = 1;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private Handler mHandler;

    private DSRvAdapter<T> adapter;
    private DSRvAdapter.RvSupport header, footer;
    private DSRvAdapter.RvSupport<T> item;
    OnItemClickListener<T> onItemClickListener;
    private boolean enablePullLoadMore = false;
    public Library_Reading_Frag(){}


    @SuppressLint("ValidFragment")
    public Library_Reading_Frag(String title, @RequestType String reqType, int category){
        Bundle bundle=new Bundle();
        bundle.putString("title",title);
        bundle.putString("reqType",reqType);
        bundle.putInt("category",category);
        setArguments(bundle);
    }

    @SuppressWarnings("WrongConstant")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle=getArguments();
        mHandler = new Handler();

        //初始化各个必要的组件
        dsRequest = new DSRequest()
                .type(bundle.getString("reqType"))
                .addParams("page",String.valueOf(1))
                //二级分类
                .setTag(Library_Reading_Frag.this)
                .addParams("typeId",String.valueOf(bundle.getInt("category")))
                .cacheType(DSUtils.NETWORK_ELSE_CACHED);
        item = new DSRvAdapter.RvSupport<T>() {
            @Override
            public int getItemViewType(T data) {
                return 0;
            }

            @Override
            public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                return ViewHolder.get(context,null,parent,R.layout.book_item,-1);
            }

            @Override
            public void convert(ViewHolder holder, T data) {

            }
        };
        Picasso picasso=Picasso.with(getContext());
        final List<ImageView> imageViews=new ArrayList<ImageView>();
        for (int i = 0; i < 6; i++) {
            ImageView imageView = new ImageView(this.getActivity());
            // 异步加载图片
            picasso.load("http://i4.buimg.com/6677832eca0fe7a8s.png").into(imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageViews.add(imageView);
        }

        header = new DSRvAdapter.RvSupport() {
            @Override
            public int getItemViewType(Object data) {
                return 0;
            }

            @Override
            public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                ViewHolder holder=ViewHolder.get(context,null,parent,R.layout.library_reading_header,-1);
                ViewPager viewPager = holder.getView(R.id.header_viewpager);
                Slide_Indicator indicator = holder.getView(R.id.header_indicator);
                PagerAdapter pagerAdapter = new PagerAdapter() {
                    @Override
                    public int getCount() {
                        return imageViews.size();
                    }

                    @Override
                    public boolean isViewFromObject(View view, Object object) {
                        return view == object;
                    }

                    @Override
                    public Object instantiateItem(ViewGroup container, int position) {
                        container.addView(imageViews.get(position));
                        return imageViews.get(position);
                    }

                    @Override
                    public void destroyItem(ViewGroup container, int position, Object object) {
                        container.removeView(imageViews.get(position));
                    }
                };
                viewPager.setAdapter(pagerAdapter);
                indicator.setupWithViewPager(viewPager);
                return holder;
            }

            @Override
            public void convert(ViewHolder holder, Object data) {

            }
        };
        enablePullLoadMore = true;
        onItemClickListener = new OnItemClickListener<T>() {
            @Override
            public void onItemClick(ViewGroup parent, View view, T t, int position) {
            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, T t, int position) {
                return false;
            }
        };
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        swipeRefreshLayout = (SwipeRefreshLayout) inflater.inflate(R.layout.simple_refreshable, container, false);
        recyclerView = (RecyclerView) swipeRefreshLayout.getChildAt(1);
        recyclerView.setBackgroundColor(Color.parseColor("#2B2C2F"));

        initView();

        return swipeRefreshLayout;
    }

    private void initView() {
        //设置布局管理器
        final GridLayoutManager layoutManager = new GridLayoutManager(getContext(),3);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position==0) return 3;
                return 1;
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        //设置item间隔
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(16, 0, 16, 16);
            }
        });


        adapter = new DSRvAdapter<T>(getContext(), new ArrayList<T>()
                , item);
        recyclerView.setAdapter(adapter);
        adapter.setHeader(header);

        //启用上拉加载功能
        if (enablePullLoadMore) {
            footer = new DSRvAdapter.RvSupport() {
                @Override
                public int getItemViewType(Object data) {
                    return 0;
                }

                @Override
                public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                    return ViewHolder.get(context, null, parent, R.layout.simple_refreshing, -1);
                }

                @Override
                public void convert(ViewHolder holder, Object data) {
                    if ((int) data == DSRvAdapter.FOOTER_STATE_PENDING)
                        holder.setText(R.id.refreshing_text, "上拉加载更多...");
                    else
                        holder.setText(R.id.refreshing_text, "正在加载更多数据...");

                }

            };
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                int lastVisibleItem = 0;

                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                        adapter.setFooter_state(adapter.FOOTER_STATE_REFRESHING);
                        dsRequest
                                .addParams("page", String.valueOf(++currentPage))
                                .build()
                                .execute(new DSRequest.DSCallback<List<T>>() {
                                    @Override
                                    public void onResponse(List<T> result) {
                                        adapter.addMoreItemData(result);
                                        L.i(TAG, "上拉加载成功");
                                    }

                                    @Override
                                    public void onFailure(String msg) {
                                        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                                    }
                                });
                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                }
            });
            adapter.setFooter(footer);
        }
        adapter.setOnItemClickListener(onItemClickListener);
//        填充数据
        dsRequest
                .addParams("page", String.valueOf(1))
                .setTag(Library_Reading_Frag.this)
                .build()
                .execute(new DSRequest.DSCallback<List<T>>() {
                    @Override
                    public void onResponse(List<T> result) {
                        adapter.setItemDatas(result);
                    }

                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                    }
                });

//        设置刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                L.i(TAG, "=>onRefresh");
                currentPage = 1;
                dsRequest
                        .addParams("page", String.valueOf(currentPage))
                        .build()
                        .execute(new DSRequest.DSCallback<List<T>>() {
                            @Override
                            public void onResponse(List<T> result) {
                                adapter.setItemDatas(result);
                                swipeRefreshLayout.setRefreshing(false);
                                L.i(TAG, "刷新成功");
                            }

                            @Override
                            public void onFailure(String msg) {
                                Toast.makeText(getContext(), msg, Toast.LENGTH_LONG).show();
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        });
            }
        });
    }
}
